package com.rpp.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @Description
 * @Author rpp
 * @Date 2020/8/4 11:29 下午
 */
@Component
public class ApplicationUtils implements ApplicationContextAware {

    /**
     * 应用上线文容器
     */
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext context) throws BeansException {
        applicationContext = context;
    }

    /**
     * 根据bean名称获取实例
     *
     * @param beanName
     * @return
     */
    public static Object getBean(String beanName) {
        return applicationContext.getBean(beanName);
    }

    /**
     * 根据名称和class获取实例
     *
     * @param beanName
     * @param cla
     * @param <T>
     * @return
     */
    public static <T> T getBean(String beanName, Class<T> cla) {
        Object obj = applicationContext.getBean(beanName, cla);
        if (obj != null) {
            return (T) obj;
        }
        return null;
    }

    /**
     * 根据class获取实例
     *
     * @param cls
     * @param <T>
     * @return
     */
    public static <T> T getBean(Class<T> cls) {
        return applicationContext.getBean(cls);
    }
}
